package com.cras.webcam.http;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by cras on 2017/6/18 0018.
 */

public class HttpServerAndroidService extends Service {
    private static final String LOG_TAG = HttpServerAndroidService.class.getName();
    private ServerBootstrap server = null;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
                Log.i(LOG_TAG,"webnet status change ");
                //区分网络状态
                //startHttpServer();
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
        return START_REDELIVER_INTENT;//系统重新构建服务，传递最后一次传递的Intent
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate(){
        super.onCreate();
        try {
            this.startHttpServer();
        }catch (Exception ex){
            Log.e(LOG_TAG,"start http server error ",ex);
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver,filter);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        this.server.stop();
    }

    private void startHttpServer(){
        Log.i(LOG_TAG,"service start http server ");
        if (server == null) {
            server = new ServerBootstrap();
        }else {
            server.stop();
        }
        new Thread(server).start();
    }
}
